import { Component, OnInit } from '@angular/core';
import { Store } from '@ngxs/store';
import { OverlayRef } from '@angular/cdk/overlay';
import { AutoUnsubscribe } from 'ngx-auto-unsubscribe-decorator';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { DemoAction, DemoSelector } from '../../store/demo';

@Component({
  selector: 'app-demo-edit',
  templateUrl: './demo-edit.component.html',
})
export class DemoEditComponent implements OnInit {
  visible = true;
  @AutoUnsubscribe() editDemoType$ = this.store.select(DemoSelector.editType);
  validateForm: FormGroup;

  constructor(
      private store: Store,
      private overlayRef: OverlayRef,
      private fb: FormBuilder,
  ) {
    this.validateForm = this.fb.group({
      id: [null],
      name: ['', [Validators.required]],
      description: [''],
      url: [''],
      git: [''],
    });
  }

  close(): void {
    this.store.dispatch(new DemoAction.CloseDemo());
  }

  ngOnInit(): void {
    this.store.select(DemoSelector.editFlag).subscribe(r => {
      if (!r)
        this.overlayRef.dispose();
    });
  }

  submit() {
    this.store.dispatch(new DemoAction.SaveDemo());
  }
}
